<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible && !planDetailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-print>
            <el-button @click="print()">打印</el-button>
          </template>
          <template v-slot:filter-download>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="false"
        row-key="id"
        :tab-index="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @exChange="exChange"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-expand>
          <table-container
            class="expandTable"
            v-model:data="expandTableInfo.data"
            :check-box="false"
            :listen-height="true"
            :tab-index="true"
            :field-list="expandTableInfo.fieldList"
            :pager="false"
            :isDynamic="false"
            style="background: #fceacb"
          >
            <template v-slot:col-preReferenceRangeStart="scope">
              <template v-if="scope.row.preItemType == 3">
                {{ scope.row.preReferenceRangeStart }} ~{{
                  scope.row.preReferenceRangeEnd
                }}
              </template>
              <template v-else>
                <span>-</span>
              </template>
            </template>
            <template v-slot:col-preCustomOptionList="scope">
              <template v-if="scope.row.preItemType == 1">
                <el-checkbox-group v-model="scope.row.checkList" disabled>
                  <el-checkbox
                    v-for="(item, index) in scope.row.preCustomOptionList"
                    :key="index + Math.random()"
                    :label="index"
                    >{{ item.itemDetailName }}</el-checkbox
                  >
                </el-checkbox-group>
              </template>
              <template v-else-if="scope.row.preItemType == 2">
                <el-radio-group v-model="scope.row.radio" disabled>
                  <el-radio
                    v-for="(item, index) in scope.row.preCustomOptionList"
                    :key="index + Math.random()"
                    :label="index"
                    >{{ item.itemDetailName }}</el-radio
                  >
                </el-radio-group>
              </template>
              <template v-else-if="scope.row.preItemType == 3">
                {{ scope.row.preCustomOptionList[0].patrolResult || '-' }}
              </template>
              <template v-else-if="scope.row.preItemType == 4">
                {{ scope.row.preCustomOptionList[0].patrolResult || '-' }}
              </template>
            </template>
          </table-container>
        </template>

        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-planOrderNo="scope">
          <span class="slip-edit" @click="showPlanDetail(scope.row)">{{
            scope.row.planOrderNo
          }}</span>
        </template>
        <template v-slot:col-preAssetName="scope">
          {{ scope.row.preAssetName }}
        </template>
        <template v-slot:col-inventoryPercent="scope">
          <span>{{ scope.row.inventoryPercent || 0 }} %</span>
        </template>
        <template v-slot:col-remindDuration="scope">
          <span
            >{{ scope.row.remindDuration || 0 }}
            {{ scope.row.remindTimeTypeValue || '-' }}</span
          >
        </template>
        <template v-slot:col-createDuration="scope">
          <span
            >{{ scope.row.createDuration || 0 }}
            {{ scope.row.createTimeTypeValue || '-' }}</span
          >
        </template>
      </table-container>
    </div>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <page-dialog
      v-if="dialogTipsInfo.visible"
      :title="dialogTipsInfo.title"
      v-model:visible="dialogTipsInfo.visible"
      :width="dialogTipsInfo.width"
      :bt-loading="dialogTipsInfo.btLoading"
      :bt-list="dialogTipsInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogTipsInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogTipsInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
    <order-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row-id="detailInfo.id"
      title="巡检任务详情"
      @returnBack="getList"
    />
    <patrol-plan-detail
      v-if="planDetailInfo.visible"
      v-model:visible="planDetailInfo.visible"
      :table-row-id="planDetailInfo.id"
      title="巡检计划详情"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="patrolRecord">
import TableContainer from '@/components/TableContainer/index'
import PageDialog from '@/components/PageDialog/index'
import patrolPlanDetail from '../patrolPlan/details'
import {
  getPlanTaskAreaCustomizeListPage,
  getPlanTaskItemAll,
  excelPlanTaskAreaDetailList,
  printPlanTaskAreaDetailList,
} from '@/api/patrol.js'
import OrderDetail from '../patrolTask/details'
import { fatchTemplateByCode } from '@/api/base.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)

const dialogTipsInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
    queryParams: {
      isPatrolRecord: 1,
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'download',
      show: proxy.$permission('patrolRecord:excelOrderList'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('patrolRecord:printOrderList'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
})
const detailInfo = reactive({
  visible: false,
  id: '',
})
const planDetailInfo = reactive({
  visible: false,
  id: '',
})
const expandTableInfo = reactive({
  data: [],
  fieldList: [
    { label: '巡检项目名称', value: 'preItemName' },
    { label: '必填', value: 'preIsRequiredValue' },
    { label: '参考范围', value: 'preReferenceRangeStart', type: 'slot' },
    {
      label: '巡检结果',
      value: 'preCustomOptionList',
      type: 'slot',
      minWidth: '240px',
    },
    { label: '正常/异常', value: 'patrolResultValue' },
    { label: '巡检人', value: 'patrolUserName' },
    { label: '备注', value: 'remark' },
  ],
})

const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
let page = reactive({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'patrol_task_area_status',
    show: false,
    hidden: true,
  },
  remindDuration: {
    label: '提醒时长',
    value: 'remindDuration',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  createDuration: {
    label: '生成于',
    value: 'createDuration',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.id = row.orderId
  detailInfo.visible = true
}
function showPlanDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  planDetailInfo.id = row.patrolPlanId
  planDetailInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function pageInfo(obj) {
  page = obj
}
function handleClose() {
  dialogTipsInfo.visible = false
}
function checkConfirm() {
  if (dialogTipsInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogTipsInfo.type === 'print') {
    printList()
  }
  dialogTipsInfo.visible = false
  dialogTipsInfo.msg = ''
}
function exportExcel() {
  //导出
  dialogTipsInfo.visible = true
  dialogTipsInfo.type = 'excel'
  dialogTipsInfo.msg = '请选择数据导出范围'
  dialogTipsInfo.btList[1].label = '导出'
  dialogTipsInfo.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.query,
    ...page,
    page: dialogTipsInfo.flag,
  }
  excelPlanTaskAreaDetailList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function print() {
  //打印
  dialogTipsInfo.visible = true
  dialogTipsInfo.type = 'print'
  dialogTipsInfo.msg = '请选择当数据打印范围'
  dialogTipsInfo.btList[1].label = '打印'
  dialogTipsInfo.flag = true
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'patrolRecord:printOrderList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogTipsInfo.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: flag,
  }
  printPlanTaskAreaDetailList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function exChange(data, expandedRows) {
  if (expandedRows.length > 0) {
    let params = {
      taskAreaId: data.id,
    }
    expandTableInfo.data = []
    getPlanTaskItemAll(params).then((resp) => {
      if (resp && resp.success) {
        expandTableInfo.data = resp.data
        expandTableInfo.data.forEach((item) => {
          if (item.preIsRequired == 0) {
            item.patrolResultValue = item.patrolResultValue
              ? item.patrolResultValue
              : '正常'
            item.patrolResult =
              item.patrolResultValue || item.patrolResultValue === 0
                ? item.patrolResultValue
                : 1
          }
          if (item.preItemType === 1) {
            let checkList = []
            item.preCustomOptionList.forEach((row, index) => {
              if (row.isChecked) {
                checkList.push(index)
              }
            })
            item['checkList'] = checkList
          } else if (item.preItemType === 2) {
            let index = item.preCustomOptionList.findIndex(
              (row) => row.isChecked
            )
            item['radio'] = index > -1 ? index : ''
          } else if (item.preItemType === 3) {
            item.preCustomOptionList[0].patrolResult =
              item.preCustomOptionList[0].patrolResult || undefined
          }
        })
      }
    })
  }
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'patrolRecordOrderList-com.slip.spd.entity.vo.patrol.PatrolTaskAreaDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      tableInfo.fieldList.unshift({
        value: 'expand',
        columnType: 'expand',
        type: 'slot',
      })
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getPlanTaskAreaCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped lang="scss">
.dialogInfo-form-title {
  width: 100%;
  padding-left: 10px;
  color: #6dc1a9;
  margin-bottom: 20px;
  span {
    color: rgb(95, 91, 91);
    font-size: 12px;
  }
}
</style>
